#-*- coding: utf-8 -*-
"""
文件说明：USB2DIO相关函数测试程序
更多帮助：www.toomoss.com
"""
from ctypes import *
import platform
from time import sleep
from usb_device import *
from usb2dio import *
from usb2lin_ex import *

if __name__ == '__main__':
    DevHandles = (c_int * 20)()
    DevHandle = 0
    # Scan device
    ret = USB_ScanDevice(byref(DevHandles))
    if(ret == 0):
        print("No device connected!")
        exit()
    else:
        print("Have %d device connected!"%ret)
        DevHandle = DevHandles[0]#选择设备0
    # Open device
    ret = USB_OpenDevice(DevHandle)
    if(bool(ret)):
        print("Open device success!")
    else:
        print("Open device faild!")
        exit()
    # Get device infomation
    USB2XXXInfo = DEVICE_INFO()
    USB2XXXFunctionString = (c_char * 256)()
    ret = DEV_GetDeviceInfo(DevHandle,byref(USB2XXXInfo),byref(USB2XXXFunctionString))
    if(bool(ret)):
        print("USB2XXX device infomation:")
        print("--Firmware Name: %s"%bytes(USB2XXXInfo.FirmwareName).decode('ascii'))
        print("--Firmware Version: v%d.%d.%d"%((USB2XXXInfo.FirmwareVersion>>24)&0xFF,(USB2XXXInfo.FirmwareVersion>>16)&0xFF,USB2XXXInfo.FirmwareVersion&0xFFFF))
        print("--Hardware Version: v%d.%d.%d"%((USB2XXXInfo.HardwareVersion>>24)&0xFF,(USB2XXXInfo.HardwareVersion>>16)&0xFF,USB2XXXInfo.HardwareVersion&0xFFFF))
        print("--Build Date: %s"%bytes(USB2XXXInfo.BuildDate).decode('ascii'))
        print("--Serial Number: ",end=' ')
        for i in range(0, len(USB2XXXInfo.SerialNumber)):
            print("%08X"%USB2XXXInfo.SerialNumber[i],end='')
        print("")
        print("--Function String: %s"%bytes(USB2XXXFunctionString.value).decode('ascii'))
    else:
        print("Get device infomation faild!")
        exit()
    # 将接口电压配为12V
    LIN_EX_CtrlPowerOut(DevHandle,2,1)
    # 将LIN1,LIN2口设置为DIO模式
    ret = DIO_Init(DevHandle,DIO_PIN_LIN1|DIO_PIN_LIN2)
    if ret != DIO_SUCCESS:
        print("DIO_Init Error ret=%d"%ret)
        exit()
    # LIN1循环输出高低电平
    for i in range(0,100):
        DIO_SetPins(DevHandle,DIO_PIN_LIN1)
        sleep(0.1)
        DIO_ResetPins(DevHandle,DIO_PIN_LIN1)
        sleep(0.1)
    # 循环读取LIN2口高低电平状态
    for i in range(0,100):
        PinValue = DIO_ReadPins(DevHandle,DIO_PIN_LIN2)
        print("PinValue = %04X"%PinValue)
        sleep(0.1)
